<template>
  <div class='container'>
    <el-dialog
      title="新增目录"
      :visible="addTagsDialogVisible"
      width="30%"
      @close='close'
      @open='open'>
      <el-form label-width="80px" :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="所属学科" prop="subjectID" v-if="!headerQuery.id">
          <el-select v-model="addForm.subjectID" placeholder="请选择">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName" style="width:300px">
          <el-input v-model="addForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { add, detail, update } from '@/api/hmmm/tags.js'
export default {
  name: 'AddTags',
  props: {
    addTagsDialogVisible: {
      type: Boolean,
      default: false
    },
    headerQuery: { // query值
      type: Object,
      required: true
    },
    tagsId: { // 标签id
      type: Object,
      required: false
    }
  },
  data () {
    return {
      addForm: { // 表单数据
        subjectID: '',
        tagName: ''
      },
      rules: {
        tagName: [
          { required: true, message: '请输入目录名称', triggle: ['blue', 'change'] }
        ]
      },
      subjectList: [] // 学科简单列表
    }
  },
  methods: {
    // 关闭对话框
    close () {
      this.$emit('update:addTagsDialogVisible', false)
      this.$refs.addForm.resetFields()
    },
    // 开启添加标签对话框时
    async open () {
      // 编辑回显
      if (this.tagsId.id) {
        const { data } = await detail(this.tagsId)
        this.addForm = data
      }
      if (!this.headerQuery.id) {
        const { data } = await simple()
        this.subjectList = data
      }
    },
    // 确认添加
    async confirmAdd () {
      let res = null
      // 确认编辑
      if (this.addForm.addDate) {
        const res = await update(this.addForm)
        if (res.status === 200) this.$message.success('添加标签成功')
      } else {
        // 确认添加
        if (this.headerQuery.id) {
          this.addForm.subjectID = +this.headerQuery.id
          res = await add(this.addForm)
        } else {
          res = await add(this.addForm)
        }
        // 成功后提示信息
        if (res.status === 200) this.$message.success('添加标签成功')
      }
      this.$emit('updateList')
      this.close()
    }
  }
}
</script>

<style scoped lang='less'></style>
